#include <string.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <driver/rmt_rx.h>
#include <driver/rmt_tx.h>
#include <soc/rmt_reg.h>
#include "driver/gpio.h" 
#include <esp_log.h>
#include <freertos/queue.h>
#include <freertos/event_groups.h>
#include "esp32s3/rom/ets_sys.h"
#include "driver/ledc.h"

#define TAG     "LEDC"

//LED闪烁初始化
void led_flash_init(void)
{
    gpio_config_t led_gpio_cfg = {
        .pin_bit_mask = (1<<GPIO_NUM_15),          //指定GPIO
        .mode = GPIO_MODE_OUTPUT,               //设置为输出模式
        .pull_up_en = GPIO_PULLUP_DISABLE,      //禁止上拉
        .pull_down_en = GPIO_PULLDOWN_DISABLE,  //禁止下拉
        .intr_type = GPIO_INTR_DISABLE,         //禁止中断
    };
    gpio_config(&led_gpio_cfg);
}


//LED呼吸灯初始化
void led_breath_init(void)
{
    //初始化一个定时器
    ledc_timer_config_t ledc_timer = {
        .speed_mode       = LEDC_LOW_SPEED_MODE,      //低速模式
        .timer_num        = LEDC_TIMER_0,     //定时器ID
        .duty_resolution  = LEDC_TIMER_12_BIT,  //占空比分辨率，这里最大值是2^12-1
        .freq_hz          = 5000,  // PWM频率,这里是5KHZ
        .clk_cfg          = LEDC_AUTO_CLK    // 时钟
    };
    ESP_ERROR_CHECK(ledc_timer_config(&ledc_timer));

    //ledc通道初始化
    ledc_channel_config_t ledc_channel = {
        .speed_mode     = LEDC_LOW_SPEED_MODE,        //低速模式
        .channel        = LEDC_CHANNEL_0,     //PWM 通道0-7
        .timer_sel      = LEDC_TIMER_0,       //关联定时器，也就是上面初始化好的那个定时器
        .gpio_num       = GPIO_NUM_15,   //设置输出PWM方波的GPIO管脚
        .duty           = 0, // 设置默认占空比为0
    };
    ESP_ERROR_CHECK(ledc_channel_config(&ledc_channel));

    //开启硬件PWM
    ledc_fade_func_install(0);
}


// 主函数
void app_main(void)
{
	#if 0
    int led_level = 0;
    led_flash_init();     //简单led闪烁
    while(1)
    {
        gpio_set_level(GPIO_NUM_15,led_level);
        vTaskDelay(pdMS_TO_TICKS(500));
        led_level = led_level?0:1;
    }
    #endif
    
    led_breath_init();      //呼吸灯
    while(1)
    {
        ledc_set_fade_with_time(LEDC_LOW_SPEED_MODE,LEDC_CHANNEL_0,4095,2000);
        ledc_fade_start(LEDC_LOW_SPEED_MODE,LEDC_CHANNEL_0,LEDC_FADE_WAIT_DONE);
        ledc_set_fade_with_time(LEDC_LOW_SPEED_MODE,LEDC_CHANNEL_0,0,2000);
        ledc_fade_start(LEDC_LOW_SPEED_MODE,LEDC_CHANNEL_0,LEDC_FADE_WAIT_DONE);
    }
}
